package info.niwota.profile;

import info.niwota.profile.client.HttpClient;
import info.niwota.profile.util.MailTemplate;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

/**
 * @author qiangli
 *
 */
public class EditSignatureActivity extends Activity {
	private static final int MENU_DONE = 1;
	private MenuItem doneMenuItem;
	private CharSequence signature;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    requestWindowFeature(Window.FEATURE_LEFT_ICON);

		setContentView(R.layout.signature_edit);

		setTitle(R.string.action_signature);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon);
		
		//
		loadPreference();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		doneMenuItem = menu.add(Menu.NONE, MENU_DONE, Menu.NONE,
				R.string.menu_done);
		doneMenuItem.setIcon(R.drawable.ic_menu_save);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case MENU_DONE:
			doFinish();
			return true;
		default:
		}
		return false;
	}
	
	
    private void doFinish() {
    	savePreference();
		finish();
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	doFinish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    
    private void loadPreference() {
		final SharedPreferences p = PreferenceManager
				.getDefaultSharedPreferences(this);
		//
		signature = p.getString(Preferences.PROFILE_SIGNATURE, "");
		
		EditText sig = (EditText) findViewById(R.id.signature_text);
		sig.setText(signature);
		
		TextView url = (TextView) findViewById(R.id.signature_link);
		final String id = p.getString(Preferences.PROFILE_ID, "");
		final String name = p.getString(Preferences.PROFILE_NAME, "");
		url.setText(MailTemplate.profileLink(id, name));
	}
    
	private void savePreference() {
		EditText sig = (EditText) findViewById(R.id.signature_text);
		final String s = trim(sig.getText().toString());
		
		//check for change
		if (s.equals(signature)) {
			return;
		}
		
		final SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor ed = pref.edit();
		//
		ed.putString(Preferences.PROFILE_SIGNATURE, s);
		//
		ed.commit();
		
		//
		HttpClient.updateProfile(this);
	}

	private static String trim(String s) {
		if (s == null) {
			return "";
		}
		return s.trim();
	}
}
